package com.moon.listener;

import com.moon.controller.OrderController;
import com.moon.dao.TAuctionMapper;
import com.moon.dao.TOrderMapper;
import com.moon.entity.TAuction;
import com.moon.entity.TOrder;
import com.moon.service.OrderService;
import com.moon.utils.JsonUtils;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

@Component
public class CloseAuctionListener {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    TAuctionMapper auctionMapper;

    @Autowired
    OrderService orderService;

    @RabbitListener(queues = "deadLetterAuctionQueue")
    public void onMsg(String task, Channel channel, Message message) throws IOException {
        try {
            System.out.println(task);
            //获取预定结束的时间
            Calendar calendar = Calendar.getInstance();
            TAuction auction = JsonUtils.toObj(task, TAuction.class);
            calendar.setTime(auction.getStartTime());
            calendar.add(Calendar.DATE, auction.getAuctionTime()-1);
            Date newDate = calendar.getTime();
            //如果当前时间早于竞拍结束时间，就重新发给交换机
            if (new Date().before(newDate)) {
                rabbitTemplate.convertAndSend("delayAuctionExchange", "closeAuction", auction.toJson());
            } else {
                //反之竞拍已结束
                TAuction auc = auctionMapper.selectOne(auction);
                //判断有无竞拍者记录
                if (auc.getTopPrice()!=null){
                    auc.setStatus(2);
                    orderService.addOrder(auc);
                } else {
                    auc.setStatus(3);
                }
                Example example = new Example(TAuction.class);
                example.createCriteria().andEqualTo("id", auc.getId());
                auctionMapper.updateByExample(auc, example);
            }
            //true批量，false单个
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //第三个参数，true代表入队 false代表出队
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            //
        }
        //
    }
}
